package com.chenlipeng.utils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;


public class ImagePreProcess {


	public static Map<String, Object> downloadImage(String url, String imgName) {
//		CloseableHttpClient httpClient = JwUtils.getHttpClient();
		DefaultHttpClient httpClient=new DefaultHttpClient();
		HttpClientContext context =HttpClientContext.create(); 
		 // 使用cookieStore方式  
		
		HttpGet getMethod = new HttpGet(url);
		List<NameValuePair> headers2=new ArrayList<NameValuePair>();
		headers2.add(new BasicNameValuePair("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"));
		headers2.add(new BasicNameValuePair("User-Agent","Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36"));
		if(headers2!=null){
			for (NameValuePair valuePair : headers2) {
				getMethod.addHeader(valuePair.getName(), valuePair.getValue());
			}
		}
		HttpResponse response = null;
		try {
			response = httpClient.execute(getMethod,context);
			CookieStroeUtil cookieStore=new CookieStroeUtil();
			cookieStore.setCookieStore(httpClient.getCookieStore());
			if("HTTP/1.1 200 OK".equals(response.getStatusLine().toString())){
				String checkCode = null;
	            if(response.getStatusLine().getStatusCode() == 200) {
	                //打印所有响应头
	            	System.out.println("请求验证码,返回的响应头的信息...");
	                Header[] headers = response.getAllHeaders();
	                for (Header header : headers) {
	                	if ((header.getName()).equals("Set-Cookie")) {
	                		String aString=header.getValue();
	                		if (aString.indexOf("CheckCode")>=0) {
	                			checkCode=aString.substring(aString.indexOf("=")+1, aString.indexOf(";"));
	                			System.out.println("验证码是====>"+checkCode);
							}
						}
	                   System.out.println(header.getName() + ": " + header.getValue());
	                }
	            }
				Map<String, Object> par=new HashMap<String, Object>();
				par.put("checkCode", checkCode);
				par.put("Cookie", cookieStore);
				return par;
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

}
